import React, { useState, useEffect } from "react";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Navigate,
  useNavigate,
  useLocation,
} from "react-router-dom";
import { Layout, Menu, theme, message } from "antd";
import {
  UserOutlined,
  VideoCameraOutlined,
  FolderOutlined,
  ExclamationCircleOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  SettingOutlined,
  LoginOutlined,
} from "@ant-design/icons";
import Login from "./pages/Login";
import VideoManagement from "./pages/VideoManagement";
import CollectionManagement from "./pages/CollectionManagement";
import ReportManagement from "./pages/ReportManagement";
import UserManagement from "./pages/UserManagement";
import LoginExample from "./components/LoginExample";
import {
  removeToken,
  getToken,
  isTokenExpired,
  getCurrentUser,
} from "./utils/auth";
import "./App.css";

const { Header, Sider, Content } = Layout;

// 基于token的认证状态管理
const useAuth = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userInfo, setUserInfo] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  // 检查认证状态
  const checkAuthStatus = () => {
    try {
      const token = getToken();

      if (!token) {
        console.log("🔐 未找到token，用户未登录");
        setIsLoggedIn(false);
        setUserInfo(null);
        return false;
      }

      // 检查token是否过期
      if (isTokenExpired(token)) {
        console.log("⏰ Token已过期，清理登录状态");
        removeToken();
        localStorage.removeItem("isLoggedIn");
        setIsLoggedIn(false);
        setUserInfo(null);
        message.warning("登录已过期，请重新登录");
        return false;
      }

      // 获取用户信息
      const user = getCurrentUser();
      console.log("✅ 认证状态有效，用户信息:", user);

      setIsLoggedIn(true);
      setUserInfo(user);
      return true;
    } catch (error) {
      console.error("❌ 认证状态检查失败:", error);
      setIsLoggedIn(false);
      setUserInfo(null);
      return false;
    }
  };

  // 组件挂载时检查认证状态
  useEffect(() => {
    const authValid = checkAuthStatus();
    console.log("🔍 初始认证检查结果:", authValid ? "已登录" : "未登录");
    setLoading(false);
  }, []);

  // 监听localStorage变化（多标签页同步）
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === "token" || e.key === "isLoggedIn") {
        console.log("📱 检测到存储变化，重新检查认证状态");
        checkAuthStatus();
      }
    };

    window.addEventListener("storage", handleStorageChange);
    return () => window.removeEventListener("storage", handleStorageChange);
  }, []);

  const login = () => {
    localStorage.setItem("isLoggedIn", "true");
    checkAuthStatus();
  };

  const logout = () => {
    console.log("🚪 用户登出，清理所有认证数据");

    // 清理所有认证相关数据
    removeToken();
    localStorage.removeItem("isLoggedIn");

    // 更新状态
    setIsLoggedIn(false);
    setUserInfo(null);

    message.success("已安全退出登录");
    setTimeout(() => {
      // 刷新页面
      window.location.reload();
    }, 500);
  };

  return {
    isLoggedIn,
    userInfo,
    loading,
    login,
    logout,
    checkAuthStatus,
  };
};

const AdminLayout: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const {
    token: { colorBgContainer },
  } = theme.useToken();
  const { logout, userInfo } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();

  const menuItems = [
    {
      key: "/admin/video",
      icon: <VideoCameraOutlined />,
      label: "视频管理",
    },
    {
      key: "/admin/collection",
      icon: <FolderOutlined />,
      label: "合集管理",
    },
    {
      key: "/admin/report",
      icon: <ExclamationCircleOutlined />,
      label: "举报管理",
    },
    {
      key: "/admin/user",
      icon: <UserOutlined />,
      label: "用户管理",
    },
  ];

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="logo">{collapsed ? "管理" : "后台管理系统"}</div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={[location.pathname]}
          items={menuItems}
          onClick={({ key }) => {
            navigate(key);
          }}
        />
      </Sider>
      <Layout>
        <Header
          style={{
            padding: 0,
            background: colorBgContainer,
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <div style={{ display: "flex", alignItems: "center" }}>
            {React.createElement(
              collapsed ? MenuUnfoldOutlined : MenuFoldOutlined,
              {
                className: "trigger",
                onClick: () => setCollapsed(!collapsed),
                style: {
                  fontSize: "18px",
                  padding: "0 24px",
                  cursor: "pointer",
                },
              }
            )}
          </div>
          <div style={{ paddingRight: "24px" }}>
            <span style={{ marginRight: "16px" }}>
              {userInfo?.username || "管理员"}
              {userInfo?.role && (
                <span
                  style={{ color: "#666", fontSize: "12px", marginLeft: "4px" }}
                >
                  ({userInfo.role})
                </span>
              )}
            </span>
            <a onClick={logout} style={{ cursor: "pointer" }}>
              退出登录
            </a>
          </div>
        </Header>
        <Content
          style={{
            margin: "24px 16px",
            padding: 24,
            minHeight: 280,
            background: colorBgContainer,
          }}
        >
          <Routes>
            <Route
              path="/admin"
              element={<Navigate to="/admin/video" replace />}
            />
            <Route path="/admin/video" element={<VideoManagement />} />
            <Route
              path="/admin/collection"
              element={<CollectionManagement />}
            />
            <Route path="/admin/report" element={<ReportManagement />} />
            <Route path="/admin/user" element={<UserManagement />} />
          </Routes>
        </Content>
      </Layout>
    </Layout>
  );
};

const App: React.FC = () => {
  const { isLoggedIn, loading } = useAuth();

  // 显示加载状态
  if (loading) {
    return (
      <div
        style={{
          height: "100vh",
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          fontSize: "16px",
        }}
      >
        正在验证登录状态...
      </div>
    );
  }

  return <Router>{isLoggedIn ? <AdminLayout /> : <Login />}</Router>;
};

export default App;
